package cserver

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"strings"
)

var _ SipsCserverModel = (*customSipsCserverModel)(nil)

type (
	// SipsCserverModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSipsCserverModel.
	SipsCserverModel interface {
		sipsCserverModel
		List(ctx context.Context, name string, status int64, page int64, limit int64) ([]*SipsCserver, error)
		Counts(ctx context.Context, name string, status int64) (int64, error)
	}

	customSipsCserverModel struct {
		*defaultSipsCserverModel
	}

	Counts struct {
		Total int64 `db:"total"`
	}
)

func (m *customSipsCserverModel) List(ctx context.Context, name string, status int64, page int64, limit int64) ([]*SipsCserver, error) {
	var sqlWhere string = m.getWhere(name, status)
	var resp []*SipsCserver
	query := fmt.Sprintf("select %s from %s %s order by id desc limit ?,?", sipsCserverRows, m.table, sqlWhere)
	if err := m.QueryRowsNoCacheCtx(ctx, &resp, query, (page-1)*limit, limit); err != nil && err != ErrNotFound {
		return nil, err
	}

	return resp, nil
}

func (m *customSipsCserverModel) Counts(ctx context.Context, name string, status int64) (int64, error) {
	var sqlWhere string = m.getWhere(name, status)
	var countTotal Counts
	var sql string = fmt.Sprintf("select count(*) as total from %s %s", m.table, sqlWhere)
	var err error = m.QueryRowNoCacheCtx(ctx, &countTotal, sql)
	return countTotal.Total, err
}

func (m *customSipsCserverModel) getWhere(gname string, status int64) string {
	var sqlWhere []string = make([]string, 0)

	if gname != "" {
		sqlWhere = append(sqlWhere, fmt.Sprintf(" names like '%s%%' ", gname))
	}

	if status > 0 {
		sqlWhere = append(sqlWhere, fmt.Sprintf(" status = %d ", status))
	}

	if len(sqlWhere) == 0 {
		return ""
	}

	var sqlStr string = strings.Join(sqlWhere, " and ")
	if sqlStr != "" {
		sqlStr = " where " + sqlStr
	}

	return sqlStr
}

// NewSipsCserverModel returns a model for the database table.
func NewSipsCserverModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) SipsCserverModel {
	return &customSipsCserverModel{
		defaultSipsCserverModel: newSipsCserverModel(conn, c, opts...),
	}
}
